package itbour.onetouchshow.activity.video.clip;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.percent.PercentRelativeLayout;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.google.gson.Gson;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.canvas.CompoundPathsBean;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.ImageTools;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.aliyun.AliRequestUtils;
import itbour.onetouchshow.widget.clip.ClipImageLayout;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class ClipActivity extends MVPBaseActivity {

    @BindView(R.id.id_clipImageLayout)
    ClipImageLayout idClipImageLayout;
    @BindView(R.id.tv_now_px)
    TextView tvNowPx;
    @BindView(R.id.ll_px_text_now)
    LinearLayout llPxTextNow;
    @BindView(R.id.tv_suggest_px)
    TextView tvSuggestPx;
    @BindView(R.id.ll_px_text_suggest)
    LinearLayout llPxTextSuggest;
    @BindView(R.id.iv_is_fit_px)
    ImageView ivIsFitPx;
    @BindView(R.id.tv_is_fit_px)
    TextView tvIsFitPx;
    @BindView(R.id.ll_fit_px)
    LinearLayout llFitPx;
    @BindView(R.id.iv_is_qrcode_work)
    ImageView ivIsQrcodeWork;
    @BindView(R.id.tv_is_qrcode_work)
    TextView tvIsQrcodeWork;
    @BindView(R.id.ll_qrcode_is_work)
    LinearLayout llQrcodeIsWork;
    @BindView(R.id.ll_clipact_tip)
    LinearLayout llClipactTip;
    @BindView(R.id.id_action_clip)
    Button idActionClip;
    @BindView(R.id.id_action_cancel)
    Button idActionCancel;
    @BindView(R.id.rl_botom)
    PercentRelativeLayout rlBotom;
    private Unbinder unbinder;

    private String IMAGEFILETYPE = ".png";
    //private ProgressDialog loadingDialog;
    //    //用于标记是否是二维码
//    private boolean isQRCode = false;
//    //用于标识是否是印品 是否


    @OnClick({R.id.id_action_cancel, R.id.id_action_clip})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.id_action_cancel:
                finish();
                break;
            case R.id.id_action_clip:
                showProgressDialogWithText("请稍等");
                clipImage();
                break;

            default:
                break;

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.acitivity_clip;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        setContentView(R.layout.acitivity_clip);
        unbinder = ButterKnife.bind(this);
        //这步必须要加
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


        String maskJson = getIntent().getStringExtra(AppConst.TOPHOTO_MASK);
        String path = getIntent().getStringExtra(AppConst.LOCAL_PHOTO_PATH);
        Gson gson = new Gson();
        CompoundPathsBean mask = gson.fromJson(maskJson, CompoundPathsBean.class);
        if (TextUtils.isEmpty(path) || !(new File(path).exists())) {
            Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
            return;
        }


        int[] whd = UIUtils.WHD();
        Bitmap bitmap = ImageTools.convertToBitmap(path, whd[0], whd[1] - UIUtils.dp2px(50)); //传图并缩放
        if (bitmap == null) {
            Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
            return;
        }

        idClipImageLayout.setData(mask, bitmap);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    private void clipImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String name = AliRequestUtils.getInstance().createFileName("image", App.getLoginBean().getUserInfo().getUserId() + "") + IMAGEFILETYPE;
                AliRequestUtils.getInstance().setName(name);

                String url = "http://itbour-user.oss-cn-hangzhou.aliyuncs.com/";
//              Bitmap bitmap = idClipImageLayout.clip();
                Bitmap bitmap = idClipImageLayout.getBitMap();
                File file = new File(Environment.getExternalStorageDirectory() + "/ClipHeadPhoto/cache/");
                if (!file.exists()) {
                    file.mkdirs();
                }
                String paths = Environment.getExternalStorageDirectory() + "/ClipHeadPhoto/cache/" + System.currentTimeMillis() + IMAGEFILETYPE;

                ImageTools.savePhotoToSDCard(bitmap, paths);


                int bitH = 0;
                int bitW = 0;
                if (bitmap != null && bitmap.getHeight() != 0) {
                    bitH = bitmap.getHeight();
                }
                if (bitmap != null && bitmap.getWidth() != 0) {
                    bitW = bitmap.getWidth();
                }


                Intent intent = new Intent();
                try {
                    App.ossClient.putObject(AliRequestUtils.getInstance().putObjectRequest(paths));

                    intent.putExtra(AppConst.LOCAL_PHOTO_PATH, paths);
                    String pathName = url + name;
                    intent.putExtra(AppConst.LOCAL_PHOTO_PATH_NAME, pathName);
                    intent.putExtra(AppConst.PHOTO_BITMAP_W, bitW);
                    intent.putExtra(AppConst.PHOTO_BITMAP_H, bitH);
                    setResult(RESULT_OK, intent);

                    L_.i("阿里云照片上传成功===" + pathName);
                } catch (ClientException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ClipActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (ServiceException e) {
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ClipActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                if (!isFinishing()) {
                    dismissProgressDialog();
                    finish();
                }

            }
        }).start();
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        setTitleText("选择照片");
    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }
}
